//
//  ViewController.m
//  成都咖啡
//
//  Created by rimi on 16/3/21.
//  Copyright © 2016年 wenhao. All rights reserved.
//

#import "ViewController.h"
#import "ItemsModel.h"
#import <BmobSDK/Bmob.h>
#import "ShoppingCenterViewController.h"

#define KTitemcellEdgeDistance 10
#define KTitemsCountInLines 3
#define kITEMCELLIDENTIFIER @"ItemCollectionCell"
#import <MapKit/MapKit.h>
#import "HomeMapViewController.h"

@interface itemcontroller ()
@property (strong, nonatomic) IBOutlet UIImageView *headimage;

@property (strong, nonatomic) IBOutlet UILabel *textlabel;


@end


@implementation itemcontroller

@end

@interface ViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>{
    NSInteger           selectIndex_;
    NSInteger           currentIndex_;
    NSMutableArray      *contentImageViews_;
    NSArray *data;
    NSMutableArray * arraydata;
    NSMutableArray * arrayLoad;
    NSDictionary * dic;
    
    
}

@property (strong, nonatomic) IBOutlet UIScrollView *scrollView;
@property (strong, nonatomic) IBOutlet UICollectionView *collectionView;
@property(nonatomic,copy)NSArray * itemsarray;//这个界面的collectionView上的数据源数组
@property (copy , nonatomic) NSString *selectedTitle;//选择的title
@property (strong, nonatomic) NSArray *centerArray;//shoppingCenter 上的cell内容数组

@property (nonatomic,strong)NSTimer *timer;

@property (strong, nonatomic) IBOutlet UIPageControl *pageControl;
@end

@implementation ViewController

- (void)dealloc {
    [_timer invalidate];
    
}


- (void)viewDidLoad {
    [super viewDidLoad];
   // CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake(32.33,100.78);
    [self initializeDataSource];
     
    
}

- (void)viewDidAppear:(BOOL)animated {

    [self initializeInterface];
}

- (void)initializeDataSource{
    selectIndex_ = 10;
    currentIndex_ = 0;
    contentImageViews_ = [NSMutableArray array];
    
//    _timer = [NSTimer scheduledTimerWithTimeInterval:2.5 target:self selector:@selector(changeHeadScrollViewImage) userInfo:nil repeats:YES];
    _timer = [NSTimer timerWithTimeInterval:2.5 target:self selector:@selector(changeHeadScrollViewImage) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
    
}

- (void)initializeInterface{
    [self setAutomaticallyAdjustsScrollViewInsets:NO];
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _scrollView
        .backgroundColor = [UIColor blackColor];
        _scrollView.contentSize = CGSizeMake(CGRectGetWidth(_scrollView.bounds)*3, CGRectGetHeight(_scrollView.bounds));
        _scrollView.contentOffset = CGPointMake(CGRectGetWidth(_scrollView.bounds), 0);
        _scrollView.pagingEnabled = YES;
        _scrollView.delegate = self;
        
        
        for (int i = 0; i<3; i++) {
            NSInteger index = [self indexWithCurrentIndex:currentIndex_+i-1 totalCount:7];
            
            UIImageView *scrollImageView = [[UIImageView alloc]initWithFrame:CGRectMake(_scrollView.bounds.size.width*i, 0, _scrollView.bounds.size.width, _scrollView.bounds.size.height)];
            scrollImageView.backgroundColor = [UIColor orangeColor];
            NSString *imageName = [NSString stringWithFormat:@"item_%ld",index+1];
            scrollImageView.image = [UIImage imageNamed:imageName];
            //        scrollImageView.image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForAuxiliaryExecutable:imageName]];
            [_scrollView addSubview:scrollImageView];
            [contentImageViews_ addObject:scrollImageView];
        }

    });

   }

#pragma make - ******** UIScrollViewDelegate ********
//timeMethod
- (void)changeHeadScrollViewImage {
    //    currentIndex_ = ++currentIndex_ % 7;
    //        [_scrollView setContentOffset:CGPointMake(CGRectGetWidth(_scrollView.bounds)*currentIndex_, 0) animated:YES];
    [_scrollView setContentOffset:CGPointMake(_scrollView.contentOffset.x+_scrollView.bounds.size.width, 0) animated:YES];
}

//scrollMethod
- (NSInteger)indexWithCurrentIndex:(NSInteger)currentIndex totalCount:(NSInteger)totalCount {
    if (currentIndex < 0) {
        currentIndex = totalCount - 1;
    }
    if (currentIndex > totalCount - 1) {
        currentIndex = 0;
    }
    return currentIndex;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView == _scrollView) {
        [self updateScrollView:scrollView];
        _pageControl.currentPage = currentIndex_;
    }
    
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    if (scrollView == _scrollView) {
         _timer.fireDate = [NSDate distantFuture];
    }
   
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    if (scrollView == _scrollView) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            _timer.fireDate = [NSDate distantPast];
        });
    }
   
}


- (void)updateScrollView:(UIScrollView *)scrollView {
    BOOL shouldUpdate = NO;
    //小于第一张图片最左边（左滑）
    if (scrollView.contentOffset.x <= 0) {
        currentIndex_ = [self indexWithCurrentIndex:currentIndex_-1 totalCount:7];
        shouldUpdate = YES;
    }
    //右滑
    else if (scrollView.contentOffset.x >= CGRectGetWidth(self.scrollView.bounds)*2) {
        currentIndex_ = [self indexWithCurrentIndex:currentIndex_+1 totalCount:7];
        shouldUpdate = YES;
    }
    
    if (!shouldUpdate) {
        return;
    }
    for (int i = 0; i<3; i++) {
        NSInteger index = [self indexWithCurrentIndex:currentIndex_+i-1 totalCount:7];
        
        UIImageView *imageView = (UIImageView *)contentImageViews_[i];
        NSString *imageName = [NSString stringWithFormat:@"item_%ld",index+1];
        
        imageView.image = [UIImage imageNamed:imageName];
    }
    //复位
    [self resumeScrollView:self.scrollView animated:YES];
    
    
}

- (void)resumeScrollView:(UIScrollView *)scrollView animated:(BOOL)animated {
    [scrollView setContentOffset:CGPointMake(CGRectGetWidth(_scrollView.bounds), 0) animated:NO];
}




#pragma mark - UIbutton action


- (IBAction)buttonWithPressed:(UIButton *)sender {
    [self performSegueWithIdentifier: @"MapViewIdentifier" sender:self];

    
}

- (IBAction)collectButtonWithPressed:(UIButton *)sender {
    [self performSegueWithIdentifier: @"collectIdentifier" sender:self];
    
}

#pragma mark - UICollectionViewDelegateFlowLayout

-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    UIEdgeInsets  edggeinsets = UIEdgeInsetsMake(KTitemcellEdgeDistance, KTitemcellEdgeDistance, KTitemcellEdgeDistance, KTitemcellEdgeDistance);
    return edggeinsets;
}

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    //    获取collectionview 的宽高
    CGFloat collectionviewwide = self.collectionView.bounds.size.width;
    CGFloat collectionviewheight = self.collectionView.bounds.size.height;
    CGFloat cellwidth = (collectionviewwide - (KTitemcellEdgeDistance * KTitemsCountInLines - 1) * (KTitemsCountInLines -1))/2+16;
    CGFloat cellheight = (collectionviewheight - (KTitemcellEdgeDistance * KTitemsCountInLines - 1) * 2)/2+15;
    return CGSizeMake(cellwidth, cellheight);
}


-(CGFloat )collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 2;
}
//
-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 10;
}



#pragma mark - UICollectionViewDelegate
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    
//    //    执行连线
    //找到选择的title（界面跳转分类页的选择方法，先拿到数组）
    self.selectedTitle = [(ItemsModel *)self.itemsarray[indexPath.row] textLabelTitle];
    
    
    
           [self performSegueWithIdentifier: @"imageViewGoingToHere" sender:self];
    
    
}

#pragma mark - UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.itemsarray.count;
}

-(UICollectionViewCell * )collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    itemcontroller *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kITEMCELLIDENTIFIER forIndexPath:indexPath];
    ItemsModel *model = self.itemsarray[indexPath.row];
    cell.textlabel.text = model.textLabelTitle;
    cell.headimage.image = [UIImage imageNamed:model.imageName];
    
    return cell;
}
//用stroyboard的线方法跳转界面，要用这个方法传值
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    
    if ([segue.destinationViewController isKindOfClass:[ShoppingCenterViewController class]]) {
        ShoppingCenterViewController *controller = segue.destinationViewController;
        //把中心页需要的数组传过去
        controller.shopListString = _selectedTitle;
       
    }
    
}

#pragma mark - 懒加载
- (NSArray * )itemsarray
{
    if (!_itemsarray) {
        ItemsModel * itemModel = [[ItemsModel alloc]init];
        _itemsarray = [itemModel gainitemtitle];
    }
    return _itemsarray;
}


@end
